package com.itheima.reggie.service.Impl;

import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.exception.BusinessException;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;


    /**
     * 添加购车
     *
     * @param shoppingCart
     * @return ShoppingCart
     */
    @Override
    public ShoppingCart addCart(ShoppingCart shoppingCart) {
        //查询购物车的菜品或套餐信息
        ShoppingCart byShoppingCart = shoppingCartMapper.findByShoppingCart(shoppingCart);
        if (byShoppingCart == null) {
            //菜品或套餐是否小于等于0
            /*if (shoppingCart.getDishId() <= 0 || shoppingCart.getSetmealId() <= 0){
                throw new BusinessException("购物菜品或套餐数量不可为小于0");
            }*/
            //完善创建时间
            byShoppingCart = shoppingCart;
            byShoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.save(byShoppingCart);
        }else {
            /*if (shoppingCart.getDishId() <= 0 || shoppingCart.getSetmealId() <= 0){
                throw new BusinessException("购物菜品或套餐数量不可为小于0");
            }*/
            byShoppingCart.setNumber(byShoppingCart.getNumber()+1);
            shoppingCartMapper.update(byShoppingCart.getId(),byShoppingCart.getNumber());
        }
        return byShoppingCart;
    }

    @Override
    public List<ShoppingCart> findAllByUserId(Long userId) {
        return shoppingCartMapper.findAllUserId(userId);
    }

    /**
     * 清空购物车
     *
     * @param userId
     * @return boolean
     */
    @Override
    public boolean deleteByUserId(Long userId) {
        return shoppingCartMapper.deleteByUserId(userId)>0;
    }
}
